/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.server.entities.finance;

import java.util.HashMap;

import javax.persistence.Id;
import javax.persistence.Transient;

import com.googlecode.objectify.Key;
import com.gwtp.investmentadvisor.server.enums.FinancialSecurityType;

/**
 * @author Sunny Gupta
 *
 */
public class FinancialSecurity {
  /**
   * The Unique Key - This is generated by app and not auto-generated by datastore.
   */
  @Id
  private String uniqueIdentifier;
  
  /**
   * The Name of the security.
   */
  private String name;
   
  /**
   * The Ticker Symbol for the Security.
   */
  private String tickerSymbol;

  /**
   * Store the FinancialMarket key.
   */
  private Key<FinancialMarket> financialMarketKey;
  
  // The alias is persisted since Enum not supported
  private int financialSecurityTypeAlias;
  
  /**
   * This string may be used to hold some custom data, specific to a particular security type.
   * This has a format of ; separated key=value parts, though this format is not enforced and the
   * user is entirely responsible for the same
   */
  private String customData;
  
  /**
   * Required for persistence.
   */
  public FinancialSecurity() {
  }
  
  /**
   * Returns the 'lightweight' view of the Security
  
  public FinancialSecurityView getSecurityView() {
    // Build FinancialSecurityView
    FinancialSecurityView view;
    if(this.uniqueIdentifier != null) {
      view = new FinancialSecurityView(this.uniqueIdentifier);
    } else {
      view = new FinancialSecurityView();
    }
    view.setName(this.name);
    // Obtain latest price
    FinancialAmount currentMarketPrice = null;
    view.setCurrentMarketPrice(null.getValue().toEngineeringString());
    view.setCurrencyCode(getFinancialMarket().getCurrency().getCurrencyCode());
    view.setExchangeName(this.getFinancialMarket().getName());
    view.setFinancialSecurityType(this.getFinancialSecurityType().toString());
    return view;
  }
   */
  
  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @return the key
   */
  public String getUniqueIdentifier() {
    return uniqueIdentifier;
  }

  private void setUniqueIdentifier() {
    // Check for null
    if (this != null && this.financialMarketKey != null && this.getFinancialSecurityType() != null) {
      this.uniqueIdentifier = createFinancialSecurityUniqueIdentifier(
          this.financialMarketKey.getName(),  
          this.getFinancialSecurityType(),
          this.tickerSymbol,
          this.customData);
    } else {
      this.uniqueIdentifier = null;
    }
    
    // Update key
    this.key = new Key<FinancialSecurity>(FinancialSecurity.class, this.uniqueIdentifier);
  }
  
  public static String createFinancialSecurityUniqueIdentifier(String marketID,
      FinancialSecurityType securityType, String tickerSymbol, String customData) {
    // Financial Market ID - Security Type - TickerSymbol - CustomData.hashCode (as String)
    String val = marketID + "_" +
            securityType.name() + "_" +
            tickerSymbol + "_" +
            customData.hashCode();
    
    return val;
  }

  /**
   * @param tickerSymbol the tickerSymbol to set
   */
  public void setTickerSymbol(String tickerSymbol) {
    // Only if different
    if (!this.tickerSymbol.equals(tickerSymbol)) {
      this.tickerSymbol = tickerSymbol;
      // Refresh UniqueIdentifier
      setUniqueIdentifier();
    }
  }

  /**
   * @return the tickerSymbol
   */
  public String getTickerSymbol() {
    return tickerSymbol;
  }

  /**
   * 
   * @param financialMarketKey
   */
  public void setFinancialMarketKey(Key<FinancialMarket> financialMarketKey) {
    // Only if different
    if (!this.financialMarketKey.equals(financialMarketKey)) {
      this.financialMarketKey = financialMarketKey;
      // Refresh UniqueIdentifier
      setUniqueIdentifier();
    }
  }

  /**
   * 
   * @return
   */
  public Key<FinancialMarket> getFinancialMarketKey() {
    return this.financialMarketKey;
  }

  /**
   * @param financialSecurityType the financialSecurityType to set
   */
  public void setFinancialSecurityType(FinancialSecurityType financialSecurityType) {
    int alias = financialSecurityType.getAlias();
    // Only if different
    if (this.financialSecurityTypeAlias != alias) {
      this.financialSecurityTypeAlias = alias;
      // Refresh UniqueIdentifier
      setUniqueIdentifier();
    }
  }

  /**
   * @return the financialSecurityType
   */
  public FinancialSecurityType getFinancialSecurityType() {
    return FinancialSecurityType.getValueFromAlias(financialSecurityTypeAlias);
  }

  public void setCustomData(String customData) {
    // Only if different
    if (!this.customData.equals(customData)) {
      this.customData = customData;
      // Refresh UniqueIdentifier
      setUniqueIdentifier();
    }
  }

  public String getCustomData() {
    return customData;
  }
  
  public HashMap<String, String> getCustomDataAsHashMap() {
    if (this.customData == null || this.customData.trim().isEmpty()) {
      return null;
    }
    
    HashMap<String, String> hashmap = new HashMap<String, String>(); 
    String[] arr = this.customData.split(";");
    for (String val : arr) {
      String[] arr2 = val.split("=");
      String vkey = arr2[0];
      String value = arr2[1];
      hashmap.put(vkey, value);
    }
    
    return hashmap;
  }
  
  /**
   * Need not be stored, but may be required by clients.
   */
  @Transient
  private Key<FinancialSecurity> key;
  
  public Key<FinancialSecurity> getKey() {
    return key;
  }
}
